package com.hnqcgczy.sgzTest.db;

import java.sql.Connection;
import java.sql.SQLException;

public class MySqlTransaction {

    private DB db;//组合方式  延迟new  定义为成员属性  马上注入值
    private Connection conn;

    //构造器   注入值
    public MySqlTransaction(DB db, boolean isAutoCommit) {
        this.db = db;
        try {
            //1、获得数据库连接
            conn = db.getConn();
            //2、改变事务提交方式
            conn.setAutoCommit(isAutoCommit);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }

    //获取设置事务为给定状态的数据库连接对象
    public Connection getConnByTran() {
        return conn;
    }

    //回滚
    public void rollbackByMe() {
        if (conn != null) {
            try {
                conn.rollback();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }

    //提交
    public void commitByMe() {
        if (conn != null) {
            try {
                conn.commit();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }

}
